var systemBiz = {
addErp:function(erp, fromSelf){
    var joinQueue = false;
    if(fromSelf && erp.bigType=="大票单") {
        joinQueue = true;
    }
    if(erp.timeType=="提前下单" || erp.bigType=="大票单") {
        
    }else {
        if(erp.cn_type=="大") {
            joinQueue = true;
        }
        else {
            if(erp.p_erp_no!="") {
                //find in datamap
                if(erpDataMap[erp.p_erp_no]!=undefined) {
                    //todo super logic here
                    joinQueue = true;
                }
            }
        }
    }
    erpDataMap[erp.erp_no] = erp;
    if(joinQueue) {
        this.onTaskJsonQueue(this.generateTaskFromErp(erp));
    }
    else {
        if(erp.bigType=="大票单") {
            var addrMap = {};
            var hunMode = false;//混装模式
            for(e0 in erpDataMap) {
                if(hunMode) break;
                var de0 = erpDataMap[e0];
                if(de0.so_no==erp.so_no) {
                    //check addr count > 1?hunMode = true
                    if(!hunMode && de0.addrs.split(" ").length>1) {
                        hunMode = true;
                    }
                    
                    if(addrMap[de0.addrs]==undefined) {
                        addrMap[de0.addrs] = de0.initBigQueueId==""?erpDataLoader.generateBigQueueId():de0.initBigQueueId;
                    }
                }
            }
            if(!hunMode) {
                var addrSeqMap = {};
                var erpSeqMap = {};
                for(e0 in erpDataMap) {
                    var de0 = erpDataMap[e0];
                    if(erpSeqMap[de0.erp_no]!=undefined) continue;
                    if(de0.so_no==erp.so_no) {
                        de0.initBigQueueId =addrMap[de0.addrs];
                        erpSeqMap[de0.erp_no]="ok";
                        if(addrSeqMap[de0.addrs]==undefined) {
                            addrSeqMap[de0.addrs]=1;
                            de0.initBigQueueGoFirst = "是";
                            if(de0.p_erp_no!="" && erpDataMap[de0.p_erp_no]!=undefined) {
                                erpDataMap[de0.p_erp_no].initBigQueueGoFirst = "是";
                            }
                        }
                        de0.initBigQueueSeq = addrSeqMap[de0.addrs];
                        if(de0.p_erp_no!="" && erpDataMap[de0.p_erp_no]!=undefined) {
                            erpDataMap[de0.p_erp_no].initBigQueueSeq = addrSeqMap[de0.addrs];
                            erpDataMap[de0.p_erp_no].initBigQueueId = addrMap[de0.addrs];
                            erpSeqMap[de0.p_erp_no]="ok";
                        }
                        addrSeqMap[de0.addrs] = addrSeqMap[de0.addrs]+1;
                    }
                }
            }
            else {
                erp.initAutoBizState = "否";
                var queueId =erpDataLoader.generateBigQueueId();
                var seq = 1;
                for(e0 in erpDataMap) {
                    var de0 = erpDataMap[e0];
                    if(de0.so_no==erp.so_no) {
                        de0.initBigQueueId =queueId;
                        de0.initBigQueueSeq = seq;
                        seq++;
                    }
                }
            }
        }
        erpDataLoader.flushErpTable();
    }
},
forceTaskIntoQueue:function(erp_no) {
    var erp = erpDataMap[erp_no];
    //valid erp
    this.addErp(erp,true);
    if(erp.p_erp_no!="" && erpDataMap[erp.p_erp_no]!=undefined) {
        this.addErp(erpDataMap[erp.p_erp_no],true);
    }
},
generateTaskFromErp:function(erp) {
    var task = {};
    task[erp.erp_no] = erp;
    if(erp.p_erp_no!="" && erpDataMap[erp.p_erp_no]!=undefined) {
        task[erp.p_erp_no]=erpDataMap[erp.p_erp_no];
    }
    return task;
},
onTimeToHandleEarlyOrder:function(){
    var time = erpDataLoader.getsys_conf_current_time();
    var nextDay =new Date(getDate(time).getTime()+(24*3600*1000));
    var stime = getDate(time).getHours()>12?(nextDay.Format("yyyy-MM-dd")+" 00:00:00"):(getDate(time).Format("yyyy-MM-dd")+" 12:00:00");
    var etime = getDate(time).getHours()>12?(nextDay.Format("yyyy-MM-dd")+" 12:00:00"):(nextDay.Format("yyyy-MM-dd")+" 00:00:00");
    consoleTool.log(time+"，又到了处理提前下单的时候了。寻求"+stime+" 到 " + etime+"之间的任务。");
    var erp =this.findEarlyOrderTask(erpDataMap,stime,etime,false);
    var count = 0;
    while(erp!=null) {
        this.onTaskJsonQueue(this.generateTaskFromErp(erp));
        //this.setTaskToTop(erp.erp_no);
        count++;
        erp =this.findEarlyOrderTask(erpDataMap,stime,etime,false);
    }
    consoleTool.log(count+"票提前下单的任务进入队列，进程结束。");
},
findEarlyOrderTask:function(dataMap,stime,etime,showLog) {
    var tempErp = null;
    for(e in dataMap) {
        var erp = dataMap[e];
        if(undefined==erp || (erp.p_erp_no=="" && erp.cn_type=="小") || erp.actCustomerTruckTime=="") continue;
        if("是"==erp.currentInSequence) continue;
        if("提前下单"!=erp.timeType) continue;
        if(getDate(etime).getTime()<
           getDate(erp.actCustomerTruckTime).getTime()) continue;
        
        if(null==tempErp) tempErp=erp;
        else {
            if(tempErp.setTopTime=="" && erp.setTopTime==""){
                if(tempErp.fen<erp.fen) {
                    tempErp = erp;
                }
            }
            else if(tempErp.setTopTime=="" && erp.setTopTime!="") {
                tempErp=erp;
            }
            else if(tempErp.setTopTime!="" && erp.setTopTime!="") {
                var tempTime = getDate(tempErp.setTopTime);
                var erpTime = getDate(erp.setTopTime);
                if(tempTime.getTime()>erpTime.getTime()) tempErp=erp;
            }
        }
    }
    if(null==tempErp) {consoleTool.log("没有找到可派的任务,停止派单.",showLog);return null;}
    else {
        consoleTool.log("找到分数最高任务："+tempErp.erp_no+" "+tempErp.p_erp_no+" | "+tempErp.fen+"分" + (tempErp.setTopTime==""?"":(" | "+tempErp.setTopTime+"置顶")), showLog);
        return tempErp;
    }
},
onTaskJsonQueue:function(task){
    consoleTool.log("一条任务进入队列");
    //计算task分值
    //更新旧队列分值
    //记录更新分值时间
    //刷新队列
    var currentQueue = this.getTaskSequence();
    
    var time =erpDataLoader.getsys_conf_current_time();
    for(a in task) {
        var erp = task[a];
        if(erp.fen==0 || erp.fen=="") {
            erp.fen = erpDataLoader.generateFen();
        }
        erp.state = "已确认/未派车";
        erp.currentInSequence="是";
        erp.joinQueueTime =time;
        erpDataMap[erp.erp_no] = erp;
    }
    consoleTool.log("新任务"+this.taskInfoToString(task));
    
    
    var currentDate = getDate(time);
    var currentFenDate = getDate(erpDataLoader.getsys_conf_current_flush_time()==""?time:erpDataLoader.getsys_conf_current_flush_time());
    var btime = currentDate.getTime()-currentFenDate.getTime();//毫秒
    var plusFen = Math.floor((btime/(60*1000*10)))*(erpDataLoader.getsys_conf_current_fen_time_param()-0);
    consoleTool.log("旧队列共有任务："+this.getQueueCount(currentQueue)+"票，与上次评分相距："+Math.floor((btime/(60*1000)))+"分钟，全部加："+plusFen+"分。");
    for(a in currentQueue) {
        var erp = erpDataMap[a];
        if(task[a]==undefined) {
            erp.fen = erp.fen-0+plusFen;
        }
    }
    erpDataLoader.setsys_conf_current_flush_time(time);
    
    consoleTool.log("新队列刷新完毕，系统自动请求派单");
    erpDataLoader.flushErpTable();
    erpDataLoader.flushTaskTable();
    this.requestPaireTaskTruck();
},
getQueueCount:function(queue) {
    var count = 0;
    for(a in queue) {
        var d = queue[a];
        if(undefined==d) {continue;}
        else if(d.p_erp_no=="") {count++;}
        else {
            count++;
            queue[d.p_erp_no]=undefined;
        }
    }
    return count;
},
taskInfoToString:function(task){
    var str = "";
    var fen = 0;
    var erp_no = "";
    for(a in task) {
        erp_no+=task[a].erp_no + " ";
        if((task[a].fen-0)>fen) fen = (task[a].fen-0);
    }
    str="交接单号："+erp_no+", 分值："+fen;
    return str;
},
doPaire:function(d1,d2){
    erpDataMap[d1.erp_no] = d1;
    erpDataMap[d2.erp_no] = d2;
    erpDataLoader.flushErpTable();
    consoleTool.log("一条任务进入队列，系统自动请求派单");
    erpDataLoader.flushTaskTable();
    this.requestPaireTaskTruck();
},
setTaskToBigBizFirst:function(erp_no) {
    var erp = erpDataMap[erp_no];
    //todo valid erp
    erp.initBigQueueGoFirst="是";
    if(erp.p_erp_no!="" && erpDataMap[erp.p_erp_no]!=undefined) {
        erpDataMap[erp.p_erp_no].initBigQueueGoFirst="是";
    }
    erpDataLoader.flushErpTable();
},
setBigBizQueueAuto:function(erp_no, initAutoBizState) {
    var erp = erpDataMap[erp_no];
    //todo valid erp
    for(e in erpDataMap) {
        var de = erpDataMap[e];
        if(erp.so_no==de.so_no) {
            de.initAutoBizState=initAutoBizState;
        }
    }
    erpDataLoader.flushErpTable();
    erpDataLoader.flushTaskTable();
},
setBigBizIntoQueue:function(erp_no,initBigQueueSeq) {
    var erp = erpDataMap[erp_no];
    //todo valid erp
    //if(erp.timeType=="提前下单") check its time to add to queue
    var tempMap = {};
    for(e in erpDataMap) {
        var de = erpDataMap[e];
        if(initBigQueueSeq!=undefined && erp.so_no==de.so_no && de.initBigQueueSeq==initBigQueueSeq) {//指定序号
            if(tempMap[e]!=undefined) continue;
            this.addErp(de,true);
            if(de.p_erp_no!="" && erpDataMap[de.p_erp_no]!=undefined) {
                tempMap[de.p_erp_no] = "ok";
                this.addErp(erpDataMap[de.p_erp_no],true);
            }
            tempMap[e] = "ok";
        }
        if(initBigQueueSeq==undefined && erp.so_no==de.so_no && de.initBigQueueGoFirst=="是" && de.fen=="0") {//指定队列
            if(tempMap[e]!=undefined) continue;
            this.addErp(de,true);
            if(de.p_erp_no!="" && erpDataMap[de.p_erp_no]!=undefined) {
                tempMap[de.p_erp_no] = "ok";
                this.addErp(erpDataMap[de.p_erp_no],true);
            }
            tempMap[e] = "ok";
        }
    }
},
updateTruckTaskState:function(truckNo, bizState) {
    var truck = truckDataMap[truckNo];
    //todo valid biz
    var bizs = this.getErpsFromTruckCurrentTask(truck.currentTask);
    truck.currentTaskState =bizState;
    
    for(e in bizs) {
        var de = bizs[e];
        de.state = truck.currentTaskState;
    }
    erpDataLoader.flushTruckTable();
    erpDataLoader.flushErpTable();
    consoleTool.log(truck.truckNo+" | "+truck.currentTask + " | " + bizState);
    if("完成装货"==bizState) {
        var bigType = "";
        var initBigQueueId = "";
        var initBigQueueSeq = "";
        var initAutoBizState = "否";
        for(e in bizs) {
            var de = erpDataMap[e];
            bigType = de.bigType;
            initBigQueueId = de.initBigQueueId;
            initBigQueueSeq = de.initBigQueueSeq;
            initAutoBizState  = de.initAutoBizState;
            if(de.bigType=="大票单") {
                bigType="大票单";
                break;
            }
        }
        if(bigType=="大票单") {
            var nextInitBigQueueSeq =(initBigQueueSeq-0+1);
            consoleTool.log("系统检测到任务"+truck.currentTask+"是大票单，已开启开启自动连续派单，自动派送"+initBigQueueId+"下一份任务，序号:"+nextInitBigQueueSeq);
            var d1 = null;
            var d2 = null;
            for(e in erpDataMap) {
                var erp = erpDataMap[e];
                if(erp.initBigQueueId==initBigQueueId && erp.initBigQueueSeq==nextInitBigQueueSeq) {
                    if(d1==null) d1=erp;
                    else if(d2==null) d2=erp;
                }
            }
            if(d1==null && d2==null) {
                consoleTool.log("系统自动检索结果：找不到"+initBigQueueId+"下一份任务，序号:"+nextInitBigQueueSeq+" ,大票单队列"+initBigQueueId+"结束。");
            }
            else {
                consoleTool.log("系统自动检索结果：找到"+initBigQueueId+"下一份任务，序号:"+nextInitBigQueueSeq+" ,交接单号："+(d1==null?"":d1.erp_no)+" " +(d2==null?"":d2.erp_no));
                if("否"==initAutoBizState) {
                    consoleTool.log("系统检测到任务"+truck.currentTask+"是大票单，未开启开启自动连续派单，等待人工处理大票单队列"+initBigQueueId+"。");
                }
                else {
                    this.setBigBizIntoQueue(d1.erp_no, nextInitBigQueueSeq);
                }
            }
        }
    }
},
getErpsFromTruckCurrentTask:function(currentTask) {
    var erps = {};
    var erp_nos = currentTask.split(" ");
    for(e in erp_nos) {
        erps[erp_nos[e]] = erpDataMap[erp_nos[e]];
    }
    return erps;
},
setTruckActive:function(truckNo){
    var truck = truckDataMap[truckNo];
    if(truck.currentTask=="" && truck.currentWorkState=="停运") {
        truck.currentWorkState = "启运";
        truck.currentInSequence = "是";
        truck.joinQueueTime = erpDataLoader.getsys_conf_current_time();
        erpDataLoader.flushTruckTable();
        consoleTool.log("一辆车进入启运状态，系统自动请求派单");
        this.requestPaireTaskTruck();
    }
},
setTruckUnActive:function(truckNo){},
setTaskToTop:function(erp_no) {
    this.setTaskTopTime(erp_no,erpDataLoader.getsys_conf_current_time());
},
unSetTaskToTop:function(erp_no) {
    this.setTaskTopTime(erp_no,"");
},
setTaskTopTime:function(erp_no, time) {
    var erp = erpDataMap[erp_no];
    //var time = erpDataLoader.getsys_conf_current_time();
    erp.setTopTime = time;
    if(erp.p_erp_no!=""){
        erpDataMap[erp.p_erp_no].setTopTime = time;
    }
    erpDataLoader.flushErpTable();
    erpDataLoader.flushTaskTable();
},
findTopTask:function(dataMap, showLog){
    var tempErp = null;
    for(e in dataMap) {
        var erp = dataMap[e];
        if(undefined==erp || (erp.p_erp_no=="" && erp.cn_type=="小")) continue;
        if("是"!=erp.currentInSequence) continue;
        
        if(null==tempErp) tempErp=erp;
        else {
            if(tempErp.setTopTime=="" && erp.setTopTime==""){
                if(tempErp.fen<erp.fen) {
                    tempErp = erp;
                }
            }
            else if(tempErp.setTopTime=="" && erp.setTopTime!="") {
                tempErp=erp;
            }
            else if(tempErp.setTopTime!="" && erp.setTopTime!="") {
                var tempTime = getDate(tempErp.setTopTime);
                var erpTime = getDate(erp.setTopTime);
                if(tempTime.getTime()>erpTime.getTime()) tempErp=erp;
            }
        }
    }
    if(null==tempErp) {consoleTool.log("没有找到可派的任务,停止派单.",showLog);return null;}
    else {
        consoleTool.log("找到分数最高任务："+tempErp.erp_no+" "+tempErp.p_erp_no+" | "+tempErp.fen+"分" + (tempErp.setTopTime==""?"":(" | "+tempErp.setTopTime+"置顶")), showLog);
        return tempErp;
    }
},
getTaskSequence:function(){
    var seqMap = {};
    // 深层复制（一层一层往下复制直到最底层）
    var tempDataMap = jQuery.extend(true, {}, erpDataMap);
    var tempErp = this.findTopTask(tempDataMap, false);
    while(null!=tempErp) {
        seqMap[tempErp.erp_no] = tempErp;
        tempDataMap[tempErp.erp_no] = undefined;
        if(""!=tempErp.p_erp_no) {
            seqMap[tempErp.p_erp_no] = tempDataMap[tempErp.p_erp_no];
            tempDataMap[tempErp.p_erp_no] = undefined;
        }
        tempErp = this.findTopTask(tempDataMap, false);
    }
    return seqMap;
},
getBigErps:function() {
    var bigErpMap = {};
    var tempMap = {};
    for(e in erpDataMap) {
        var erp = erpDataMap[e];
        if(undefined==erp) continue;
        if("大票单"!=erp.bigType || ("大票单"==erp.bigType && erp.so_no=="")) continue;
        if(tempMap[erp.so_no]!=undefined) continue;
        var queueMap = {};
        for(e0 in erpDataMap) {
            var de0 = erpDataMap[e0];
            if(de0.so_no==erp.so_no) {
                if(queueMap[de0.initBigQueueId]!=undefined) continue;
                for(e1 in erpDataMap) {
                    var de1 = erpDataMap[e1];
                    if(de1.so_no==erp.so_no && de1.initBigQueueId==de0.initBigQueueId) {
                        bigErpMap[de1.erp_no] = de1;
                    }
                }
            }
        }
        tempMap[erp.so_no] = "ok";
    }
    return bigErpMap;
},
requestPaireTaskTruck:function(){
    //get highest fen task to send
    //get highest fen truck to use (now random)
    consoleTool.log("开始搜寻分数最高的任务");
    var tempErp = this.findTopTask(erpDataMap, true);
    if(tempErp==null)return;
    
    consoleTool.log("开始搜寻可用车辆")//分数最高的车辆");
    var tempTruck = null;
    var truckPool = [];
    for(e in truckDataMap) {
        var truck = truckDataMap[e];
        if(truck.currentTask!="" || truck.currentWorkState=="停运")continue;
        truckPool.push(truck);
    }
    if(0==truckPool.length){consoleTool.log("没有找到可用的拖车,停止派单.-------");return;}
    else {
        tempTruck = truckPool[Math.round((truckPool.length-1)*Math.random())];
        consoleTool.log("找到车辆："+tempTruck.truckNo+" | "+tempTruck.truckTeam+" | 车辆退出接单队列");//+" | "+tempTruck.fen+"分");
        //生成派单结果
        if(tempErp.p_erp_no!="") {
            tempErp.currentInSequence =erpDataMap[tempErp.p_erp_no].currentInSequence= "否";
            tempErp.truckNo =erpDataMap[tempErp.p_erp_no].truckNo=tempTruck.truckNo;
            tempErp.state =erpDataMap[tempErp.p_erp_no].state=erpDataLoader.getsys_conf_auto_handle()=="0"?"已派车/未推送":"已派车/已推送/终端未确认";
        } else if(tempErp.p_erp_no=="" && tempErp.cn_type=="大") {
            tempErp.currentInSequence ="否";
            tempErp.truckNo =tempTruck.truckNo;
            tempErp.state =erpDataLoader.getsys_conf_auto_handle()=="0"?"已派车/未推送":"已派车/已推送/终端未确认";
        }
        
        tempTruck.currentInSequence="否";
        erpDataLoader.flushErpTable();
        erpDataLoader.flushTaskTable();
        
        if(erpDataLoader.getsys_conf_auto_handle()=="0") {
            consoleTool.log("平台当前处于［调度中心手动控制派单结果］模式，配对结果未推送给车队。请调度尽快确认。本轮派单结束。-------");
        }
        else {
            consoleTool.log("平台当前处于［系统自动处理派单结果］模式，配对结果已经自动短信推送给给车队调度和司机。本轮派单结束。-------");
            tempTruck.currentTask = tempErp.erp_no+" "+tempErp.p_erp_no;
            tempTruck.currentTaskState = "已派车/已推送/终端未确认";
        }
        erpDataLoader.flushTruckTable();
    }
}
};
